package com.otod.commons.filemanger.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Iterator;
import java.util.LinkedList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.otod.commons.filemanger.bo.FileBasicInfo;
import com.otod.commons.tools.UserEnv;
import com.otod.commons.utils.DateUtils;
import com.otod.commons.utils.RandomUtil;
import com.otod.commons.utils.StringUtils;
import com.otod.commons.web.BaseController;
import com.otod.sys.file.service.IFileService;
import com.otod.sys.vo.FileVo;

/**
 * 文件操作Controller
 * @author jqiu
 */
@Controller
@RequestMapping("/file")
public class FileTestController extends BaseController {
	
	@Autowired
	private IFileService fileService;
 
    /***************************************************
     * URL: /rest/controller/upload  
     * upload(): receives files
     * @param request : MultipartHttpServletRequest auto passed
     * @param response : HttpServletResponse auto passed
     * @return LinkedList<FileMeta> as json format
     ****************************************************/
    @RequestMapping(value="/upload", method = RequestMethod.POST)//
    public @ResponseBody LinkedList<FileBasicInfo> upload(MultipartHttpServletRequest request, HttpServletResponse response) {
        //1. build an iterator
         Iterator<String> itr =  request.getFileNames();
         MultipartFile mpf = null;
         
         LinkedList<FileBasicInfo> files = new LinkedList<FileBasicInfo>();
         FileBasicInfo fileMeta = null;
 
         //2. get each file
         while(itr.hasNext()){
 
             //2.1 get next MultipartFile
             mpf = request.getFile(itr.next()); 
             System.out.println(mpf.getOriginalFilename() +" uploaded! "+files.size());
 
             //2.2 if files > 10 remove the first from the list
             if(files.size() >= 10)
                 files.pop();
 
             //2.3 create new fileMeta
             fileMeta = new FileBasicInfo();
             fileMeta.setCname(mpf.getOriginalFilename());
             fileMeta.setSname(RandomUtil.getUUID());
             fileMeta.setSize(BigDecimal.valueOf(mpf.getSize()/1024));	//kb
//             fileMeta.setFileType(mpf.getContentType());
             String fileExt = getFileExt(fileMeta.getCname());
             fileMeta.setFileExt(StringUtils.isEmpty(fileExt)?"无":fileExt);
 
             try {
//                fileMeta.setBytes(mpf.getBytes());
 
                 // copy file to local disk (make sure the path "e.g. D:/temp/files" exists)
                String filePath = UserEnv.getProp("file.upload.root");
                File file = new File(filePath);
                if(!file.exists()){
                	file.mkdirs();
                }
                 FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream(filePath + File.separator + mpf.getOriginalFilename()));
 
            } catch (IOException e) {
                e.printStackTrace();
            }
             
             FileVo vo = new FileVo();
             vo.setFileSize(BigDecimal.valueOf(mpf.getSize()));
             vo.setFileName(fileMeta.getCname());
             vo.setFileType(fileMeta.getFileExt());
             super.setInsertOperInfo(vo);
             fileService.insert(vo);
             
             //2.4 add to files
             fileMeta.setBusiId(vo.getUuid());
             files.add(fileMeta);
         }
        // result will be like this
        // [{"fileName":"app_engine-85x77.png","fileSize":"8 Kb","fileType":"image/png"},...]
         
        return files;
    }
    /***************************************************
     * URL: /rest/controller/get/{value}
     * get(): get file as an attachment
     * @param response : passed by the server
     * @param value : value from the URL
     * @return void
     ****************************************************/
    @RequestMapping(value = "/get/{value}/g.do", method = RequestMethod.GET)
     public void get(HttpServletResponse response,@PathVariable String value){
//    	FileBasicInfo getFile = new FileBasicInfo();
//    	FileBasicInfo getFile = files.get(Integer.parseInt(value));
    	FileVo vo = fileService.getById(value);
    	String filePath = UserEnv.getProp("file.upload.root");
        File file = new File(filePath + File.separator + vo.getFileName());
         try {      
                response.setContentType(vo.getFileType());
                response.setHeader("Content-disposition", "attachment; filename=\""+vo.getFileName()+"\"");
                InputStream is = new FileInputStream(file);
                IOUtils.copy(is, response.getOutputStream());
//                FileCopyUtils.copy(getFile.getBytes(), response.getOutputStream());
         }catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
         }
     }
    
    @RequestMapping(value = "/picture/{id}/g.do", method = RequestMethod.GET)
    public void picture(HttpServletRequest request, HttpServletResponse response, @PathVariable String id) {
    	FileVo vo = fileService.getById(id);
    	String filePath = UserEnv.getProp("file.upload.root");
        File file = new File(filePath + File.separator + vo.getFileName());
//    	String fileUploadDirectory = request.getSession().getServletContext().getRealPath("uploadfiles");
//    	FileBasicInfo fileMeta = (FileBasicInfo) fileService.get(FileBasicInfo.class, id);
//        File file = new File(fileUploadDirectory+"/"+fileMeta.getNewFilename());
        response.setContentType(vo.getFileType());
        response.setContentLength(vo.getFileSize().intValue());
        try {
            InputStream is = new FileInputStream(file);
            IOUtils.copy(is, response.getOutputStream());
            is.close();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 获取文件扩展名
     * @param s
     * @return
     */
    private String getFileExt(String s) {
        String s1; // = new String();
        int i = 0;
        int j = 0;
        if (s == null) {
            return null;
        }
        i = s.lastIndexOf('.') + 1;
        j = s.length();
        s1 = s.substring(i, j);
        if (s.lastIndexOf('.') > 0) {
            return s1;
        } else {
            return "";
        }
    }
    
   
}